<template>
  <!-- 侧边栏回显 -->
  <div
    v-if="dialogVisible4"
    class="custom-dialog"
    :modal="false"
    :style="{ 'margin-left': 'auto', 'margin-right': 0, right: 0 }"
    :close-on-click-modal="false"
  >
    <el-form :model="formAsid" label-position="right" label-width="100px">
      <el-form-item label="id:" class="right-align-form">
        <el-input disabled v-model="formAsid.id"></el-input>
      </el-form-item>

      <el-form-item label="编码:" class="right-align-form">
        <el-input disabled v-model="formAsid.ytflbh"></el-input>
      </el-form-item>
      <el-form-item label="上级分类:">
        <el-select clearable v-model="formAsid.ytfl" placeholder="请选择:">
          <el-option
            v-for="asideCategory in asideOptions"
            :key="asideCategory.value"
            :label="asideCategory.label"
            :value="asideCategory.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称:" class="right-align-form" required>
        <el-input v-model="formAsid.flmc"></el-input>
      </el-form-item>

      <!-- 是否启用单选框 -->
      <el-form-item label="是否启用:">
        <el-switch v-model="formAsid.state"></el-switch>
      </el-form-item>

      <el-form-item label="备注:" class="right-align-form">
        <el-input v-model="formAsid.remark"></el-input>
      </el-form-item>
      <!-- <el-form-item label="层级:" class="right-align-form">
        <el-input v-model="formAsid.level"></el-input>
        
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="submitAside">提交</el-button>
        <el-button type="danger" @click="deleteAside">删除</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 主表内容回显 -->
  <div
    v-if="dialogVisible3"
    class="custom-dialog"
    :modal="false"
    :style="{ 'margin-left': 'auto', 'margin-right': 0, right: 0 }"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" label-position="right" label-width="100px">
      <!-- 用途编码 -->
      <el-form-item label="材质编码:">
        <el-input v-model="formData.ytbm" disabled placeholder="系统自动生成:"></el-input>
      </el-form-item>
      <el-form-item label="材质分类:" required>
        <el-select clearable v-model="formData.ytfl" placeholder="请选择:">
          <el-option
            v-for="parentCategory in categoryOptions"
            :key="parentCategory.value"
            :label="parentCategory.label"
            :value="parentCategory.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="上级用途:">
        <el-select v-model="formData.sjyt" placeholder="请选择:">
          <el-option
            v-for="definitionsCategory in definitionsOptions"
            :key="definitionsCategory.value"
            :label="definitionsCategory.label"
            :value="definitionsCategory.value"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <!-- 用途名称 -->
      <el-form-item label="材质名称:" required>
        <el-input v-model="formData.ytmc"></el-input>
      </el-form-item>
      <el-form-item label="材质字母:" required>
        <el-input v-model="formData.czzm"></el-input>
      </el-form-item>
      <el-form-item label="密度:" required>
        <el-input v-model="formData.md"></el-input>
      </el-form-item>
      <el-form-item label="识别码:" required>
        <el-input v-model="formData.sbm"></el-input>
      </el-form-item>

      <!-- 是否启用单选框 -->
      <el-form-item label="是否启用:">
        <el-switch v-model="formData.state"></el-switch>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注:">
        <el-input v-model="formData.bz"></el-input>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitMain">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 分类回显内容 -->
  <!-- v-model="dialogVisible1" -->
  <div
    v-if="dialogVisible1"
    class="custom-dialog"
    :modal="false"
    :style="{ 'margin-left': 'auto', 'margin-right': 0, right: 0 }"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" label-position="right" label-width="100px">
      <el-form-item label="材质分类编号:">
        <el-input
          v-model="formData.categoryNumber"
          disabled
          placeholder="系统自动生成"
        ></el-input>
      </el-form-item>
      <!-- 上级分类下拉框 -->
      <el-form-item label="上级分类:">
        <el-select clearable v-model="formData.parentCategory" placeholder="请选择">
          <el-option
            v-for="parentCategory in categoryOptions"
            :key="parentCategory.value"
            :label="parentCategory.label"
            :value="parentCategory.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称:" required>
        <el-input v-model="formData.categoryName"></el-input>
      </el-form-item>
      <el-form-item label="是否启用:">
        <el-switch v-model="formData.enabled"></el-switch>
      </el-form-item>
      <el-form-item label="备注:">
        <el-input v-model="formData.remarks"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--用途定义回显内容  -->
  <!-- v-model="dialogVisible2" -->
  <div
    v-if="dialogVisible2"
    class="custom-dialog"
    :modal="false"
    :style="{ 'margin-left': 'auto', 'margin-right': 0, right: 0 }"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" label-position="right" label-width="100px">
      <!-- 用途编码 -->
      <!-- handleAction2 -->
      <el-form-item label="材质编码:">
        <el-input v-model="formData.ytbm" disabled placeholder="系统自动生成:"></el-input>
      </el-form-item>
      <!-- 分类 -->
      <el-form-item label="材质分类:" required>
        <el-select clearable v-model="formData.ytfl" placeholder="请选择:">
          <el-option
            v-for="parentCategory in categoryOptions"
            :key="parentCategory.value"
            :label="parentCategory.label"
            :value="parentCategory.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 用途名称 -->
      <el-form-item label="材质名称:" required>
        <el-input v-model="formData.ytmc"></el-input>
      </el-form-item>
      <el-form-item label="材质字母:" required>
        <el-input v-model="formData.czzm"></el-input>
      </el-form-item>
      <el-form-item label="密度:" required>
        <el-input v-model="formData.md"></el-input>
      </el-form-item>
      <el-form-item label="识别码:" required>
        <el-input v-model="formData.sbm"></el-input>
      </el-form-item>

      <!-- 是否启用单选框 -->
      <el-form-item label="是否启用:">
        <el-switch v-model="formData.state"></el-switch>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注:">
        <el-input v-model="formData.bz"></el-input>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitDefn">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 页面布局 -->
  <div class="common-layout">
    <el-container>
      <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
        <!-- 头部按钮 -->
        <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
          <div>
            <el-button @click="searchButton" type="primary"> 查询</el-button>
            <el-button @click="handleAction1" type="success">增加分类</el-button>
            <el-button @click="handleAction2" type="success">增加定义</el-button>
            <el-button @click="handleWarning0" type="warning">启用</el-button>
            <el-button @click="handleWarning1" type="danger">停用</el-button>
            <el-button @click="handleDelete" type="danger">删除</el-button>
          </div>
          <!-- <div class="title">材质</div> -->
        </el-row>
        <!-- style="text-align: center" -->
        <!-- background:rgb(241,244,243) ; -->
        <div
          style="margin-left:12.6rem;height: 30px;width=100%; background:rgb(241,244,243);margin-bottom: 0;position: relative; display: flex; justify-content: flex-start;"
        >
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="inputBm"
            placeholder="编码"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="inputMc"
            placeholder="名称"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-header>
      <el-container>
        <el-aside
          width="12.5rem"
          :style="{
            'z-index': '1',
            'min-width': '12.5rem',
            height: dynamicHeight + 'px',
            'max-height': dynamicHeightYtfl,
            'overflow-y': 'auto',
            'margin-left': '6rem',
            'border-right': '1px solid #ccc',
          }"
        >
          <!-- style="background: linear-gradient(to right, #f7faff, #ecf9ff)" -->
          <!-- 侧边树状 -->
          <div class="down-tree">
            <el-scrollbar>
              <el-tree
                :data="ytflTreedata"
                :props="defaultProps"
                @node-click="handleNodeClick"
                :highlight-current="true"
              />
            </el-scrollbar>
          </div>
          <!-- <div class="vertical-line"></div>
          <div class="vertical-line1"></div>
          <div class="vertical-line2"></div> -->
          <!-- <div ref="verticalLine3" class="vertical-line3"></div> -->
        </el-aside>
        <el-container>
          <!-- style="background: linear-gradient(to right, #f9f9fc, #fef5f0)" -->
          <!-- padding: 0, 10%, 0, 0 -->
          <!-- tyle="width: 76.9%" -->
          <el-main style="padding: 2px 2px 0 2px">
            <!-- 头部按钮 -->
            <!--  @row-dblclick="handleTableRowClick" -->
            <!--大屏的高度  height="776" -->
            <!--小屏的高度  height="725" -->
            <!--单选高亮显示：   highlight-current-row  -->
            <el-table
              v-loading="loading"
              ref="table"
              :data="tableData"
              border
              stripe
              :cell-style="cellStyle"
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              @row-dblclick="handleRowClick"
              @row-click="RowClick"
              :row-style="rowState"
              :row-key="(row:any) => row.id"
              :max-height="screenHeight"
              :height="screenHeight"
              :summary-method="getSummaries"
              show-summary
            >
              <el-table-column fixed type="index" width="60" align="center" />
              <el-table-column fixed type="selection" width="50" align="" />
              <el-table-column fixed prop="id" label="id" width="60" align="center" />
              <el-table-column prop="ytbm" label="编码" width="70" align="" />
              <el-table-column prop="ytmc" label="名称" width="120" />
              <el-table-column prop="czzm" label="材质字母" width="120" />
              <el-table-column prop="md" label="密度" width="120" />
              <el-table-column prop="sbm" label="识别码" width="120" />
              <el-table-column prop="fq" label="分类编码" width="90" align="" />
              <el-table-column prop="ytfl" label="分类名称" width="120" />
              <el-table-column prop="state" label="状态" width="60" />
              <el-table-column prop="lx" label="数据类型" width="90" />
              <el-table-column prop="remark" label="备注" />
              <!-- <el-table-column
                fixed="right"
                prop="level"
                label="层级"
                width="60"
                align="center"
              /> -->
            </el-table>
          </el-main>
          <el-footer style="height: 20px">
            <div class="demo-pagination-block">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="limit"
                :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
                :small="true"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              /></div
          ></el-footer>
          <!-- <el-footer style="background: linear-gradient(to right, #f9f9fc, #fef5f0)"
            >Footer</el-footer
          > -->
        </el-container>
        <el-aside width="20%" :style="{ 'border-left': '1px solid #ccc' }"></el-aside>
      </el-container>
    </el-container>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { ElTable, TableColumnCtx } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Calendar,
  CircleCloseFilled,
  ArrowRight,
} from "@element-plus/icons-vue";
import { ElButton, ElDialog, dialogEmits, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import axios from "../axios/axiosInstance";
import Cookies from "js-cookie";

// 日期中文
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
const router = useRouter();
// 权限控制
const searchButtonPermissions = ref(false);
const handleAction1Permissions = ref(false);
const handleAction2Permissions = ref(false);
const handleWarning0Permissions = ref(false);
const handleWarning1Permissions = ref(false);
const handleDeletePermissions = ref(false);
const submitAsidePermissions = ref(false);
const deleteAsidePermissions = ref(false);
const submitMainPermissions = ref(false);
const submitFormPermissions = ref(false);
const submitDefnPermissions = ref(false);

const menuId = ref(4);
const buttonVariables = {
  searchButtonPermissions,
  handleAction1Permissions,
  handleAction2Permissions,
  handleWarning0Permissions,
  handleWarning1Permissions,
  submitAsidePermissions,
  handleDeletePermissions,
  deleteAsidePermissions,
  submitMainPermissions,
  submitFormPermissions,
  submitDefnPermissions,
};

const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");

  axios({
    url: "/select/Permissions/Button/A",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
// 表头
const state = reactive({
  circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
  squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
  sizeList: ["small", "", "large"] as const,
});
// 退出登录
const handleCommand = (command: string | number | object) => {
  if (command == "a") {
    Cookies.remove("userName");
    router.push("/");
  }
};
// 计算高度
const screenHeight = ref(null);
const dynamicHeight = ref(null);
const dynamicHeightYtfl = ref(null);

const getScreenHeight = () => {
  console.log(window.innerHeight);
  screenHeight.value = window.innerHeight - 146 - 42 + 55;
  dynamicHeight.value = `${window.innerHeight - 55 - 42 + 55}px`;
  dynamicHeightYtfl.value = window.innerHeight - 120 - 42 + 55;
};
getScreenHeight();
const { circleUrl, squareUrl, sizeList } = toRefs(state);
const activeIndex = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {};

// 背景色
const verticalLine3 = ref(null);
// 分页
const page = ref(1);
const limit = ref(50);
const total = ref(50);
const loading = ref(false);
const selectCookies = () => {};
selectCookies();
const handleSizeChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/search/Pagination/B/A",
      method: "post",
      data: {
        userName: userName,
        page: page.value,
        limit: limit.value,
        inputMc: inputMc.value,
        inputBm: inputBm.value,
      },
    }).then((res) => {
      if (res.data.definitionsList.length === 0) {
        ElMessage({
          message: "无权限访问!",
          type: "warning",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
        loading.value = false;
        return;
      }
      const definitionsList = res.data.definitionsList;
      total.value = definitionsList[0].total;
      tableData.value = definitionsList.map((item: any) => ({
        state: item.state === 0 ? "启用" : "未启用",
        ytmc: item.ytmc,
        ytbm: item.ytbm,
        ytfl: item.ytfl,
        czzm: item.czzm,
        md: item.md,
        sbm: item.sbm,
        id: item.id,
        level: item.level,
        remark: item.remark,
        fq: item.fq,
        lx: item.lx === 0 ? "分类" : "材质",
      }));
      loading.value = false;
    });
  });
};
const handleCurrentChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/search/Pagination/B/A",
      method: "post",
      data: {
        userName: userName,
        page: page.value,
        limit: limit.value,
        inputMc: inputMc.value,
        inputBm: inputBm.value,
      },
    }).then((res) => {
      if (res.data.definitionsList.length === 0) {
        ElMessage({
          message: "无权限访问!",
          type: "warning",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
        loading.value = false;
        return;
      }
      const definitionsList = res.data.definitionsList;
      total.value = definitionsList[0].total;
      tableData.value = definitionsList.map((item: any) => ({
        state: item.state === 0 ? "启用" : "未启用",
        ytmc: item.ytmc,
        ytbm: item.ytbm,
        ytfl: item.ytfl,
        czzm: item.czzm,
        md: item.md,
        sbm: item.sbm,
        id: item.id,
        level: item.level,
        remark: item.remark,
        fq: item.fq,
        lx: item.lx === 0 ? "分类" : "材质",
      }));
      loading.value = false;
    });
  });
};
// 搜索框
const inputMc = ref("");
const inputBm = ref("");

const searchButton = () => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/search/Pagination/B/A",
      method: "post",
      data: {
        userName: userName,
        page: page.value,
        limit: limit.value,
        inputMc: inputMc.value,
        inputBm: inputBm.value,
      },
    }).then((res) => {
      if (res.data.definitionsList.length === 0) {
        ElMessage({
          message: "搜索不到内容!",
          type: "warning",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
        total.value = 0;
        loading.value = false;
        return;
      }
      const definitionsList = res.data.definitionsList;
      total.value = definitionsList[0].total;
      tableData.value = definitionsList.map((item: any) => ({
        state: item.state === 0 ? "启用" : "未启用",
        ytmc: item.ytmc,
        ytbm: item.ytbm,
        ytfl: item.ytfl,
        czzm: item.czzm,
        md: item.md,
        sbm: item.sbm,
        id: item.id,
        level: item.level,
        remark: item.remark,
        fq: item.fq,
        lx: item.lx === 0 ? "分类" : "材质",
      }));
      loading.value = false;
    });
  });
};
// const input1 = ref('')
// 合计行

interface SummaryMethodProps<T = Product> {
  columns: TableColumnCtx<T>[];
  data: T[];
}
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = ` ${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "";
    }
    sums[index] = "";
  });

  return sums;
};
// 弹窗
const dialogButton = ref(false);
const dialogVisible1 = ref(true);
const dialogVisible2 = ref(false);
// 修改弹窗
const buttonText = ref("添加材质分类");

const handleAction1 = () => {
  dialogVisible1.value = true;
  dialogVisible2.value = false;
  dialogVisible3.value = false;
  dialogVisible4.value = false;
  formData.value.parentCategory = "";
  formData.value.categoryName = "";
  formData.value.enabled = "";
  formData.value.remarks = "";
};
const handleAction2 = () => {
  formData.value.czzm = "";
  formData.value.sbm = "";
  formData.value.md = "";
  formData.value.ytbm = "";
  formData.value.ytfl = "";
  formData.value.ytmc = "";
  formData.value.state = true;
  formData.value.bz = "";
  dialogVisible1.value = false;
  dialogVisible2.value = true;
  dialogVisible3.value = false;
  dialogVisible4.value = false;
};
// Aside内容修改
const submitAside = () => {
  const stateValue = formAsid.value.state ? 0 : 1;
  const userName = Cookies.get("userName");
  ElMessageBox.confirm("确认修改吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      axios({
        url: "/update/Classify/B/A",
        method: "post",
        data: {
          userName: userName,
          id: formAsid.value.id,
          ytflbh: formAsid.value.ytflbh,
          flmc: formAsid.value.flmc,
          state: stateValue,
          remark: formAsid.value.remark,
          ytfl: formAsid.value.ytfl,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.message,
            type: "success",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
          selectpurposes();
          return;
        }
        ElMessage({
          message: res.data.message,
          type: "error",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
      });
    })
    .catch(() => {});
};
// Aside删除
const deleteAside = () => {
  ElMessageBox.confirm("确认删除吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      const userName = Cookies.get("userName");
      axios({
        url: "/delete/Classify/B/A",
        method: "post",
        data: {
          userName: userName,
          ytflbh: formAsid.value.ytflbh,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.message,
            type: "success",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
          selectpurposes();
          // formAsid.ytfl
          dialogVisible4.value = false;
          dialogVisible1.value = true;
          return;
        }
        ElMessage({
          message: res.data.message,
          type: "error",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
      });
    })
    .catch(() => {});
};

// Main内容修改
const submitMain = () => {
  if (formData.value.ytfl == "") {
    ElMessage({
      message: "材质分类必须选择!!!",
      type: "error",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  const stateValue = formData.value.state ? 0 : 1;
  const userName = Cookies.get("userName");
  axios({
    url: "/update/Definition/B/A",
    method: "post",
    data: {
      czzm: formData.value.czzm,
      md: formData.value.md,
      sbm: formData.value.sbm,
      userName: userName,
      ytbm: formData.value.ytbm,
      ytfl: formData.value.ytfl,
      ytmc: formData.value.ytmc,
      state: stateValue,
      bz: formData.value.bz,
      czzm: formData.value.czzm,
      md: formData.value.md,
      sbm: formData.value.sbm,
    },
  }).then((res) => {
    ElMessageBox.confirm("确认修改吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.message,
            type: "success",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
          selectpurposes();
          return;
        }
        ElMessage({
          message: res.data.message,
          type: "error",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
      })
      .catch(() => {});
  });
};
// 用途分类下拉框
const categoryOptions = ref([]);
const parentCategory = ref([]);
const definitionsOptions = ref([]);
const definitionsCategory = ref([]);
const asideOptions = ref([]);
const asideCategory = ref([]);

// 用途提交
const submitDefn = () => {
  if (!formData.value.ytfl) {
    ElMessage.error({
      message: "请选择分类",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  if (!formData.value.ytmc) {
    ElMessage.error({
      message: "请填写材质名称",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  if (!formData.value.czzm) {
    ElMessage.error({
      message: "请填写材质字母",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  if (!formData.value.md) {
    ElMessage.error({
      message: "请填写密度",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  if (!formData.value.sbm) {
    ElMessage.error({
      message: "请填写识别码",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  const stateValue = formData.value.state ? 0 : 1;
  const userName = Cookies.get("userName");
  axios({
    url: "/insert/Definition/B/A",
    method: "post",
    data: {
      czzm: formData.value.czzm,
      md: formData.value.md,
      sbm: formData.value.sbm,
      userName: userName,
      ytfl: formData.value.ytfl,
      sjyt: formData.value.sjyt,
      ytmc: formData.value.ytmc,
      state: stateValue,
      remark: formData.value.bz,
      parentCategory: formData.value.parentCategory,
    },
  }).then((res) => {
    ElMessageBox.confirm("确认保存吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.message,
            type: "success",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
          formData.value.ytfl = "";
          formData.value.ytmc = "";
          formData.value.state = true;
          formData.value.remarks = "";
          formData.value.czzm = "";
          formData.value.md = "";
          formData.value.sbm = "";
          selectpurposes();
          return;
        }
        ElMessage({
          message: res.data.message,
          type: "error",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
      })
      .catch(() => {});
  });
};
// 分类提交
const submitForm = () => {
  if (!formData.value.categoryName) {
    // 使用 Element Plus 的 Message 组件弹出提示信息
    ElMessage.error({
      message: "请填写分类名称",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
    return;
  }
  ElMessageBox.confirm("确认保存吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  })
    .then(() => {
      // 在这里执行表单提交逻辑
      const stateValue = formData.value.enabled ? 0 : 1;
      const userName = Cookies.get("userName");
      axios({
        url: "/insert/Classify/B/A",
        method: "post",
        data: {
          userName: userName,
          flmc: formData.value.categoryName,
          state: stateValue,
          remark: formData.value.remarks,
          parentCategory: formData.value.parentCategory,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.message,
            type: "success",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
          handleAction1();
          selectpurposes();
          return;
        }
        ElMessage({
          message: res.data.message,
          type: "error",
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
        });
      });
    })
    .catch(() => {});
};
// 分类回显
// 分类回显按钮
const handleButtonClick = (event) => {
  dialogButton.value = false;
  formData.value.categoryNumber = "";
  formData.value.categoryName = "";
  formData.value.enabled = true;
  formData.value.remarks = "";
};
// 分类
const formData = ref({
  ytbm: "",
  parentCategory: "", // 分类下拉框
  ytfl: "",
  ytmc: "",
  state: true,
  bz: "",
  enabled: true,
});
const handleRowClick = (row) => {};

const handleTableRowClick = (row) => {
  // 设置弹窗可见
  dialogButton.value = true;
};

const ytflTreedata: ref<Tree[]> = ref([]);

const defaultProps = {
  children: "children",
  label: "label",
};
// 查看材质分类和材质定义
const selectpurposes = () => {
  // 查看是否登录
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");

    return;
  }
  axios({
    url: "/select/Purposes/B/A",
    method: "post",
    data: {
      userName: userName,
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    // 材质分类侧边栏
    const classifyList = res.data.classifyList;
    if (classifyList == null) {
      return;
    }
    // 创建一个映射，将每个节点的ID与对应节点的引用关联起来
    const nodeMap = new Map();

    // 构建树状结构
    const rootNodes = [];
    classifyList.forEach((item) => {
      const node = {
        index: item.id,
        label: item.flmc,
        children: [],
      };
      nodeMap.set(item.ytflbh, node);

      if (item.parentBh === -1) {
        // 如果是顶级节点，直接放入根节点数组
        rootNodes.push(node);
      } else {
        // 否则，找到父节点，并将当前节点放入父节点的children数组中
        const parentNode = nodeMap.get(item.parentBh);
        if (parentNode) {
          parentNode.children.push(node);
        } else {
          // 如果找不到父节点，可以考虑将当前节点放入根节点数组
          rootNodes.push(node);
        }
      }
    });
    // ytflTreedata.value[0].children = rootNodes;
    ytflTreedata.value = rootNodes;
    // 更新分类下拉框
    categoryOptions.value = classifyList
      .filter((item) => item.flmc !== "材质分类")
      .map((item) => ({
        label: item.flmc,
        value: item.id,
      }));

    parentCategory.value = classifyList
      .filter((item) => item.flmc !== "材质分类")
      .map((item) => ({
        label: item.flmc,
        value: item.id,
      }));

    //侧边栏分类下拉框
    asideOptions.value = classifyList.map((item) => ({
      label: item.flmc,
      value: item.id,
    }));
    asideCategory.value = classifyList.map((item) => ({
      label: item.flmc,
      value: item.id,
    }));
    // 更新 data

    // 表格Main,材质定义
    const definitionsList = res.data.definitionsList;
    total.value = res.data.total;
    tableData.value = definitionsList.map((item) => ({
      state: item.state === 0 ? "启用" : "未启用",
      ytmc: item.ytmc,
      ytbm: item.ytbm,
      ytfl: item.ytfl,
      id: item.id,
      // level: item.level,
      remark: item.remark,
      fq: item.fq,
      czzm: item.czzm,
      md: item.md,
      sbm: item.sbm,
      lx: item.lx === 0 ? "分类" : "材质",
    }));
    // 更新材质下拉框
    const downDefinitionList = res.data.downDefinitionList;
    definitionsOptions.value = downDefinitionList.map((item) => ({
      label: item.ytmc,
      value: item.ytmc,
    }));
    definitionsCategory.value = downDefinitionList.map((item) => ({
      label: item.ytmc,
      value: item.ytmc,
    }));
  });
};

selectpurposes();
interface Tree {
  label: string;
  children?: Tree[];
}
// 每次点击侧边栏，树状结构触发，修改表格内容
const flmc = ref("");
const handleNodeClick = (data: Tree) => {
  page.value = 1;
  flmc.value = data.label;
  loading.value = true;
  const id = data.index;
  tableData.value = [];
  nextTick(() => {
    axios({
      url: "/select/Definition/flmc/B/A",
      method: "post",
      data: {
        flmc: data.label,
        page: page.value,
        limit: limit.value,
        id: id,
      },
    }).then((res) => {
      // 表格Main,材质定义
      const definitionsList = res.data.definitionsList;
      if (definitionsList.length == 0) {
        total.value = 0;
        return;
      }
      total.value = definitionsList.length;
      tableData.value = definitionsList.map((item) => ({
        state: item.state === 0 ? "启用" : "未启用",
        ytmc: item.ytmc,
        ytbm: item.ytbm,
        ytfl: item.ytfl,
        id: item.id,
        czzm: item.czzm,
        md: item.md,
        sbm: item.sbm,
        level: item.level,
        remark: item.remark,
        fq: item.fq,
        lx: item.lx === 0 ? "分类" : "材质",
      }));
      const useClassify = res.data.useClassify;
      if (id != 1) {
        formAsid.value.id = useClassify.id;
        formAsid.value.ytflbh = useClassify.ytflbh;
        formAsid.value.ytfl = "";
        formAsid.value.flmc = useClassify.flmc;
        (formAsid.value.state = useClassify.state === 0 ? true : false),
          (formAsid.value.remark = useClassify.remark);
        formAsid.value.level = useClassify.level;
      }

      dialogVisible4.value = true;
      dialogVisible1.value = false;
      dialogVisible2.value = false;
      dialogVisible3.value = false;
    });
  });
  loading.value = false;
};

// 头部按钮
const selectedRows = ref([]);
const table = ref();
const rowTable = ref([]);
const dialogVisible3 = ref(false);
const dialogVisible4 = ref(false);

const formAsid = ref({
  id: "",
  ytflbh: "",
  flmc: "",
  state: true,
  remark: "",
  level: "",
  ytfl: "",
} as any);
const formRight = ref({
  ytbm: "",
  ytfl: "",
  ytmc: "",
  state: "",
  remark: "",
} as any);

const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};

// 审核
const handleWarning0 = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    const userName = Cookies.get("userName");
    ElMessageBox.confirm("确认启用吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        axios({
          url: "/update/State0/B/A",
          method: "post",
          data: {
            userName: userName,
            ytmc: selectedRows.value[0].ytmc,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              message: res.data.message,
              type: "success",
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
            });
            selectpurposes();
            return;
          }
          ElMessage({
            message: res.data.message,
            type: "error",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      message: "请选择一行进行启用操作",
      type: "warning",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
  }
};
const handleWarning1 = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    const userName = Cookies.get("userName");
    ElMessageBox.confirm("确认停用吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        axios({
          url: "/update/State1/B/A",
          method: "post",
          data: {
            userName: userName,
            ytmc: selectedRows.value[0].ytmc,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              message: res.data.message,
              type: "success",
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
            });
            selectpurposes();
            return;
          }
          ElMessage({
            message: res.data.message,
            type: "error",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      message: "请选择一行进行弃用操作",
      type: "warning",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
  }
};
// 删除
const handleDelete = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    const userName = Cookies.get("userName");
    ElMessageBox.confirm("确认删除吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
      .then(() => {
        axios({
          url: "/delete/Definition/B/A",
          method: "post",
          data: {
            userName: userName,
            id: selectedRows.value[0].id,
            ytmc: selectedRows.value[0].ytmc,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              message: res.data.message,
              type: "success",
              center: true,
              showClose: true,
              grouping: true,
              offset: window.screen.height / 9,
            });
            selectpurposes();
            return;
          }
          ElMessage({
            message: res.data.message,
            type: "error",
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage({
      message: "请选择一行进行删除操作",
      type: "error",
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
    });
  }
};
// 点击侧边栏触发
const isCollapse = ref(true);
const handleItemClick = (index: string) => {
  if (index.index == "1-1") {
    router.push("/Purposes");
  }
  if (index.index == "1-2") {
    router.push("/Material");
  }
  if (index.index == "2-1") {
    router.push("/MaterialsFixed");
  }
  if (index.index == "2-2") {
    router.push("/AssistDemand");
  }
  if (index.index == "3-1") {
    router.push("/AssistMaterialDetails");
  }
  if (index.index == "3-2") {
    router.push("/AssistDosage");
  }
};
const handleClose = (key: string, keyPath: string[]) => {};
// Main表格
const tableData = ref([]);
// // 设置表头样式
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const RowClick = (row, selection) => {
  // 主表点击
  dialogVisible3.value = true;
  dialogVisible1.value = false;
  dialogVisible2.value = false;
  dialogVisible4.value = false;
  table.value.toggleRowSelection(row);

  formData.value.ytbm = row.ytbm;
  // formData.value.ytfl = row.ytfl;
  formData.value.ytmc = row.ytmc;
  formData.value.state = row.state === "启用" ? true : false;
  formData.value.remark = row.remark;
  formData.value.czzm = row.czzm;
  formData.value.md = row.md;
  formData.value.sbm = row.sbm;
};

// const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
//   return {
//     borderColor: "#E9E9E7", // 设置边框颜色
//   };
// };
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    // #E9E9E7
    // D9D9D7   C9C9C7 A9A9A7
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
</script>
<style scoped>
/* 悬停 */
/* #f9f9fc, #fef5f0 */
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.custom-dialog {
  position: fixed;
  top: 9em;
  left: 50%;
  width: 20%;
}

/* 侧边树状 */
::v-deep .el-tree-node__content {
  height: 4vh;
  line-height: inherit;
}
.title {
  font-size: 18px;
}
.demo-pagination-block {
  float: right;
}
::v-deep .el-table .cell {
  padding: 0;
}
::v-deep .el-header {
  padding: 0;
}
.down-tree {
  height: 100%;
}
.el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}
.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}
.demo-basic .block:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
.demo-basic .block {
  flex: 1;
}
.flex-grow {
  flex-grow: 1;
}
</style>
